﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Kaesoft.Hospedaje.Entities;
using Telerik.Windows.Controls;
using Kaesoft.Hospedaje.Common;

namespace Kaesoft.Hospedaje.Shell
{
    public partial class MarcoTrabajoView : UserControl
    {
        public MarcoTrabajoView()
        {
            InitializeComponent();
        }
        private void RadRibbonButton_Click(object sender, RoutedEventArgs e)
        {
            AbrirVentana(((RadRibbonButton)sender).DataContext as Opcion);
        }

        private void AbrirVentana(Opcion opcion)
        {
            try
            {
                Assembly assembly;
                RadTabItem item;

                if (!OpcionAbierta(opcion))
                {
                    item = ObtenerTabItem(opcion);
                    item.IsSelected = true;
                    opcion.ensamblado = opcion.ensamblado ?? string.Empty;

                    if (!opcion.ensamblado.Equals(string.Empty) && !opcion.control.Equals(string.Empty))
                    {
                        assembly = Assembly.Load(opcion.ensamblado + ", Version=1.0.0.0");
                        var view = assembly.CreateInstance(opcion.control);

                        var viewModel = assembly.CreateInstance(opcion.control + "Model");

                        PropertyInfo propInfo = view.GetType().GetProperty("DataContext");
                        propInfo.SetValue(view, viewModel, null);

                        ((Common.ViewModelBase) viewModel).OnError += MarcoTrabajoView_OnError;
                        ((Common.ViewModelBase) viewModel).ActivarOperaciones(opcion);
                        ((Common.ViewModelBase) viewModel).NotificarDataContext(opcion);

                        item.Content = view;
                    }

                    radTabControl.Items.Add(item);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        void MarcoTrabajoView_OnError(object sender, ViewModelBaseErrorArgs e)
        {
            var errorpanelvm = ((MarcoTrabajoViewModel)DataContext).PanelErroresViewModel;
            if (errorpanelvm != null)
                errorpanelvm.Errores = e.GetErrors();
        }

        private bool OpcionAbierta(Opcion opcion)
        {
            foreach (RadTabItem item in radTabControl.Items)
            {
                if (item.Tag.Equals(opcion))
                {
                    item.IsSelected = true;
                    return true;
                }
            }
            return false;
        }

        private RadTabItem ObtenerTabItem(Opcion opcion)
        {
            RadTabItem item = new RadTabItem();
            StackPanel s;
            var color = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255,0,82,155));

            RadButton boton = new RadButton() 
            {
                Content = "X", 
                Tag = item, 
                Style = Application.Current.Resources["Facturacion_XButton"] as Style
            };
            TextBlock texto = new TextBlock() { Text = opcion.nombre, Margin = new Thickness(0, 0, 5, 0), Width = 90, FontWeight = System.Windows.FontWeights.Bold };

            boton.Click += new RoutedEventHandler(boton_Click);

            s = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Horizontal };
            s.Children.Add(texto);
            s.Children.Add(boton);
            item.Tag = opcion;
            item.Header = s;
            return item;
        }

        void boton_Click(object sender, RoutedEventArgs e)
        {
            RadButton boton = sender as RadButton;

            try
            {
                var x = (Common.ViewModelBase)(((UserControl)(((RadTabItem)(boton.Tag)).Content)).DataContext);

                if (x.IsDirty)
                {
                    MessageWindowView msgWindowView = new MessageWindowView();
                    MessageWindowViewModel msgWindowViewModel = new MessageWindowViewModel("Existen cambios pendientes en la pantalla. Desea salir?", 
                                                                                            MessageBoxButtons.OkCancel, MessageBoxIcon.Information);
                    msgWindowView.DataContext = msgWindowViewModel;
                    msgWindowViewModel.Closing += (msgsender, ev) =>
                                            {
                                                msgWindowView.Close();
                                                if (ev.Data != MessageBoxResult.OK) return;
                                                radTabControl.Items.Remove(boton.Tag);
                                                ((MarcoTrabajoViewModel)DataContext).PanelErroresViewModel.Cerrar(null);
                                            };
                    msgWindowView.ShowDialog();
                }
                else
                {
                    radTabControl.Items.Remove(boton.Tag);
                    ((MarcoTrabajoViewModel)DataContext).PanelErroresViewModel.Cerrar(null);
                }
            }
            catch (Exception)
            {
                
            }
        }

        private void radTabControl_SelectionChanged(object sender, RadSelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count == 1)
                {
                    var header = ((StackPanel)((RadTabItem)(e.AddedItems[0])).Header).Children.Where(c => c.GetType() == typeof(TextBlock)).FirstOrDefault();
                    ((TextBlock)header).FontWeight = FontWeights.Bold;

                    ((MarcoTrabajoViewModel)DataContext).WorkspaceActual = ((UserControl)((RadTabItem)e.AddedItems[0]).Content).DataContext as Kaesoft.Hospedaje.Common.ViewModelBase;
                }
                if (e.RemovedItems.Count == 1)
                {
                    var header = ((StackPanel)((RadTabItem)(e.RemovedItems[0])).Header).Children.Where(c => c.GetType() == typeof(TextBlock)).FirstOrDefault();
                    ((TextBlock)header).FontWeight = FontWeights.Normal;

                    if (((RadTabControl)sender).Items.Count == 0)
                        ((MarcoTrabajoViewModel)DataContext).WorkspaceActual = null;
                }
            }
            catch (Exception)
            {
                
            }
        }
    }
}
